const app = getApp();
const util = require('../../../../utils/util.js');
const api = require('../../../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    platform: "",//客户端平台
    circleid: '',//圈子id
    shareOpenid: '',//分享人openid
    joinDetailId: '',//加入的详情id
    dataInfo: {},// 数据
    popupInfo: { "show": true, "isError": 0, "errorMessage": "" },
    ticket: { "userInfoShow": false,"userInfo": []},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    var platform = wx.getSystemInfoSync().platform;
    _this.setData({
      circleid: options.circleid,
      shareOpenid: options.shareOpenid,
      joinDetailId: options.joinDetailId,
      platform: platform,
    })
    _this.getShareTicket();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 获取分享人分享出来的票种信息
   */
  getShareTicket: function(){
    var _this = this;
    var circleid = _this.data.circleid;
    var shareOpenid = _this.data.shareOpenid;
    var joinDetailId = _this.data.joinDetailId;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.joinDetailId = joinDetailId;
        data.shareOpenid = shareOpenid;
        data.circleid = circleid;
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Interest_GetShareTicket, data).then(function (res) {
          if (res.code == 200) {
            var json = res.result.json;
            var isOwnReceive = json.isOwnReceive;
            if (isOwnReceive){
              // 被自己领取
              util.showToast("您已领取过此票种，请加入圈子", "none");
              _this.setData({
                ["popupInfo.show"]: false
              })
            }
            _this.setData({
              dataInfo: res.result.json
            })
          } else {
            util.showToast(res.message, "none");
            _this.setData({
              ["popupInfo.isError"]: 1,
              ["popupInfo.errorMessage"]: res.message
            })
          }
        });
      });
    }
  },

  /**
   * 进入圈子详情页
   */
  navigateToCircledetails: function (e) {
    var _this = this;
    var circleid = _this.data.circleid;
    wx.navigateTo({
      url: '../../../../ucenter/pages/ucenter/personcenter/editdetails/circledetails/circledetails?circleid=' + circleid,
    })
  },

  /**
   * 进入用户主页
   */
  navigateToPersonhome: function (e) {
    var openid = e.currentTarget.dataset.openid;
    wx.navigateTo({
      url: '../../../../ucenter/pages/ucenter/personhome/personhome?openid=' + openid
    })
  },
  
  /**
   * 领取票种
   */
  receiveTicket: function () {
    var _this = this;
    var dataInfo = _this.data.dataInfo;
    var ordInterest = dataInfo.ordInterest;
    if (ordInterest.itemTypeIdentification == 1){
      // 线下圈子，填写线下圈子用户信息
      var userInfo = _this.data.ticket.userInfo;
      if(userInfo.length <= 0){
        var data = {};
        data.realname = "";
        data.phonenumber = "";
        data.age = "";
        data.gender = 1;
        data.wechat = "";
        data.remark = "";
        data.isHidden = false;
        userInfo.push(data);
        _this.setData({
          ["ticket.userInfo"]: userInfo,
        })
      }
      _this.setData({
        ["ticket.userInfoShow"]: true
      })
    }else{
      _this.receiveTicketQuery();
    }
  },

  /**
   * 领取票种：请求
   */
  receiveTicketQuery: function(){
    var _this = this;
    var circleid = _this.data.circleid;
    var shareOpenid = _this.data.shareOpenid;
    var joinDetailId = _this.data.joinDetailId;
    var openid = app.globalData.logininfo.openid;
    var ordInterest = _this.data.dataInfo.ordInterest;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.joinDetailId = joinDetailId;
        data.shareOpenid = shareOpenid;
        data.circleid = circleid;
        data.openid = openid;
        data.access_token = res.access_token;
        if (ordInterest.itemTypeIdentification == 1) {
          // 线下圈子，填写线下圈子用户信息
          data.examplesUserInfo = JSON.stringify(_this.data.ticket.userInfo);
        }
        util.post(api.Interest_ReceiveTicket, data).then(function (res) {
          if (res.code == 200) {
            util.showToast("领取成功！", "success");
            _this.setData({
              ["ticket.userInfoShow"]: false,
              ["ticket.userInfo"]: [],
              ["popupInfo.show"]: false
            })
          } else {
            util.showToast(res.message, "none");
          }
        });
      });
    }
  },

  /**
   * 上一步
   */
  userInfoReturn: function(){
    var _this = this;
    _this.setData({
      ["ticket.userInfoShow"]: false,
    })
  },

  /**
   * 成员信息：编辑切换
   */
  userInfoEditor: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var isHidden = _this.data.ticket.userInfo[index].isHidden;
    _this.setData({
      ["ticket.userInfo[" + index + "].isHidden"]: !isHidden
    })
  },

  /**
   * 成员信息：姓名输入事件
   */
  realnameInput: function (e) {
    var _this = this;
    var value = e.detail.value;
    var index = e.target.dataset.index;
    _this.setData({
      ["ticket.userInfo[" + index + "].realname"]: String(value).trim()
    })
  },

  /**
   * 成员信息：手机号输入事件
   */
  phoneInput: function (e) {
    var _this = this;
    var value = e.detail.value;
    var index = e.target.dataset.index;
    _this.setData({
      ["ticket.userInfo[" + index + "].phone"]: value
    })
  },

  /**
   * 成员信息：微信号输入事件
   */
  wechatInput: function (e) {
    var _this = this;
    var value = e.detail.value;
    var index = e.target.dataset.index;
    _this.setData({
      ["ticket.userInfo[" + index + "].wechat"]: value
    })
  },

  /**
   * 成员信息：年龄输入事件
   */
  ageInput: function (e) {
    var _this = this;
    var value = e.detail.value;
    var index = e.target.dataset.index;
    if (parseInt(value) <= 0) {
      value = 1;
    }
    _this.setData({
      ["ticket.userInfo[" + index + "].age"]: value
    })
  },

  /**
   * 成员信息：备注输入事件
   */
  remarkInput: function (e) {
    var _this = this;
    var value = e.detail.value;
    var index = e.target.dataset.index;
    _this.setData({
      ["ticket.userInfo[" + index + "].remark"]: value
    })
  },

  /**
   * 成员信息：性别切换
   */
  genderTap: function (e) {
    var _this = this;
    var value = e.currentTarget.dataset.value;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["ticket.userInfo[" + index + "].gender"]: value
    })
  },

  /**
   * 成员信息：手机号的input的鼠标移出事件
   */
  phoneBlur: function (e) {
    var _this = this;
    var index = e.target.dataset.index;
    var value = e.detail.value;
    if (value != null && String(value).length > 0) {
      _this.checkPhone(value);
    }
  },

  /**
   * 校验手机号
   */
  checkPhone: function (phone) {
    var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (!myreg.test(phone)) {
      util.dialogAlert("请输入正确的手机号");
      return false;
    }
    return true;
  },

  /**
   * 成员信息：下一步
   */
  userInfoNext: function () {
    var _this = this;
    var userInfo = _this.data.ticket.userInfo;
    var flag = true;
    for (var i = 0; i < userInfo.length; i++) {
      var realname = userInfo[i].realname;
      var phone = userInfo[i].phone;
      if (realname == null || String(realname).trim().length <= 0) {
        util.dialogAlert("请输入姓名");
        flag = false;
      }
      if (phone == null || String(phone).trim().length <= 0) {
        util.dialogAlert("请输入手机号");
        flag = false;
      }
      if (!_this.checkPhone(phone)) {
        flag = false;
      }
    }
    // 提交
    if (flag) {
      _this.receiveTicketQuery();
    }
  },

  /**
   * 立即加入
   */
  useJoinCircleByAmountDetail: function(){
    var _this = this;
    var joinDetailId = _this.data.joinDetailId;
    var openid = app.globalData.logininfo.openid;
    var circleid = _this.data.circleid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.interestJoinDetailId = joinDetailId;
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Interest_UseJoinCircleByAmountDetail, data).then(function (res) {
          if (res.code == 200) {
            util.showToast("加入成功！", "success");
            setTimeout(function () {
              _this.navigateToCircleInfo(circleid);
            }, 1000)
          } else {
            util.showToast(res.message, "none");
          }
        });
      });
    }
  },

  /**
   * 进入圈子详情页面
   */
  navigateToCircleInfo: function (circleid) {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var data = {};
    data.circleid = circleid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        _this.userIsCircleJoinQuery(api.Home_UserIsCircleJoinApiUrl, data);
      })
    }
  },

  /**
   * 校验用户是否为已加入的圈子：请求
   */
  userIsCircleJoinQuery: function (url, data) {
    var _this = this;
    util.post(url, data).then(function (res) {
      var userIsCircleJoin = false;
      if (res.code == 200) {
        userIsCircleJoin = res.result.userIsCircleJoin;
      }
      if (userIsCircleJoin) {
        // 已加入
        wx.redirectTo({
          url: '../../../../ucenter/pages/ucenter/personcenter/editdetails/circleinteraction/circleinteraction?circleid=' + data.circleid,
        })
      } else {
        util.showToast("加入圈子失败", "none");
      }
    });
  },
})